<template>
  <div class="koi-flex">
    <KoiCard>
      <div class="text-16px">传递参数：{{ routeParam }}</div>
      <div class="text-16px font-bold m-t-16px">前端加密参数，后端解密数据 Demo</div>
      <el-segmented v-model="segmentedValue" :options="segmentedOptions" class="max-w-600px m-y-16px" @change="handleChangeSegmented" />
      <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
        <el-form-item label="姓名" prop="userName">
          <el-input class="max-w-220px" v-model="form.userName" placeholder="请输入公告名称" clearable />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number :min="1" :max="200" class="max-w-220px" v-model="form.age" placeholder="请输入数字" clearable />
        </el-form-item>
        <el-button type="primary" icon="Search" plain :loading="confirmLoading" @click="handleConfirm">Test Interface</el-button>
        <div class="m-y-16px text-14px">{{ segmentedValue }}</div>
        <div v-if="customStrings" class="m-t-16px text-14px">{{ customStrings || "NULL" }}</div>
      </el-form>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="testParamPage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiMsgSuccess, koiMsgError } from "@/utils/koi.ts";
import { responseEncrypt, requestDecrypt, postDecryptEncrypt, decryptEncryptArray } from "@/api/test/dept/index.ts";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";

const route = useRoute();
const { t } = useI18n();
// 重置参数使用
let routeParam = ref();

onMounted(() => {
  routeParam.value = route.params.testId || ""; // 有值
});

// form表单Ref
const formRef = ref<any>();
// form表单
let form = ref<any>({
  userName: "安兹乌尔恭",
  age: 18
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
    // 若 form 重置不放入这里面，则失效，直接使用默认的上方 let form，同时使用一个 form 导致
    form.value = {
      userName: undefined,
      age: undefined
    };
  });
};

/** 表单规则 */
const rules = reactive({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  age: [{ required: true, message: "请输入用户年龄", trigger: "blur" }]
});

const segmentedValue = ref("返回加密 Demo");

const segmentedOptions = ["返回加密 Demo", "请求加密 Demo", "Post请求和返回都加密 Demo", "测试数组 Demo", "Get请求和返回都加密 Demo"];

const handleChangeSegmented = () => {
  if (segmentedValue.value == "返回加密 Demo") {
    form.value = {
      userName: "安兹乌尔恭",
      age: 18
    };
  }
  if (segmentedValue.value == "请求加密 Demo") {
    form.value = {
      userName: "于长生",
      age: 19
    };
  }
  if (segmentedValue.value == "Post请求和返回都加密 Demo") {
    form.value = {
      userName: "于心",
      age: 20
    }; 
  }
  if (segmentedValue.value == "测试数组 Demo") {
    form.value = {
      userName: "于天才",
      age: 21
    };
  }     
  if (segmentedValue.value == "Get请求和返回都加密 Demo") {
    form.value = {
      userName: "于无敌",
      age: 22
    };
  }    
};

// 按钮是否显示Loading
const confirmLoading = ref(false);
const customStrings = ref<any>();

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (segmentedValue.value == "返回加密 Demo") {
        try {
          form.value = {
            userName: "安兹乌尔恭",
            age: 18
          };
          const res: any = await responseEncrypt(form.value);
          customStrings.value = res.data;
          confirmLoading.value = false;
          koiMsgSuccess(t("msg.success"));
          resetForm();      
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }

      if (segmentedValue.value == "请求加密 Demo") {
        try {
          const res: any = await requestDecrypt(form.value);
          customStrings.value = res.data;
          confirmLoading.value = false;
          koiMsgSuccess(t("msg.success"));
          resetForm();       
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }

      if (segmentedValue.value == "Post请求和返回都加密 Demo") {
        try {
          form.value = {
            userName: "于心",
            age: 20
          }; 
          const res: any = await postDecryptEncrypt(form.value);         
          customStrings.value = res.data;
          confirmLoading.value = false;
          koiMsgSuccess(t("msg.success"));    
          resetForm();   
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }

      if (segmentedValue.value == "测试数组 Demo") {
        try {
          form.value = {
            userName: "于天才",
            age: 21
          };          
          const res: any = await decryptEncryptArray(form.value);            
          customStrings.value = res.data;
          confirmLoading.value = false;
          koiMsgSuccess(t("msg.success"));
          resetForm();          
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }

      if (segmentedValue.value == "Get请求和返回都加密 Demo") {
        try {
          form.value = {
            userName: "于无敌",
            age: 22
          }; 
          customStrings.value = "Get 请求不适合前端请求参数加密";
          confirmLoading.value = false;
          koiMsgSuccess(t("msg.success"));    
          resetForm();   
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }
    } else {
      koiMsgError(t("msg.validFail"));
      confirmLoading.value = false;
    }
  });
};
</script>

<style scoped></style>
